package com.fulizhe.catlocal.integration.springboot.config;

import javax.sql.DataSource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;
import com.zaxxer.hikari.HikariDataSource;

/**
 * 实现CAT对于 JdbcTemplate的埋点
 * @author LQ
 *
 */
@Aspect
@Component
public class JdbcTemplateAspect {

	@Around("execution(* org.springframework.jdbc.core.JdbcTemplate.query*(..))")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		Transaction t = Cat.newTransaction("SQL", "JdbcTemplate");

		String sql = joinPoint.getArgs()[0].toString();
		Cat.logEvent("SQL.Method", "select", Message.SUCCESS, sql);

		String url = switchDataSource(((JdbcTemplate) joinPoint.getTarget()).getDataSource());
		Cat.logEvent("SQL.Database", url);

		Object returnObj = null;
		try {
			returnObj = joinPoint.proceed();
			t.setStatus(Transaction.SUCCESS);
		} catch (Exception e) {
			Cat.logError(e);
			throw e;
		} finally {
			t.complete();
		}

		return returnObj;

	}

	protected String switchDataSource(DataSource dataSource) throws NoSuchFieldException, IllegalAccessException {
		String url = null;

		if (dataSource.getClass().getSimpleName().contains("HikariDataSource")) {
			url = ((HikariDataSource) dataSource).getJdbcUrl();
		} /*
			 * else if
			 * (dataSource.getClass().getSimpleName().contains("DruidDataSource"
			 * )) { url = ((DruidDataSource) dataSource).getUrl(); }
			 */

		return url;
	}
}
